// +----------------------------------------------------------------------
// | JavaWeb_EleVue_Pro前后端分离旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2021 上海JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <javaweb520@gmail.com>
// +----------------------------------------------------------------------
// | 免责声明:
// | 本软件框架禁止任何单位和个人用于任何违法、侵害他人合法利益等恶意的行为，禁止用于任何违
// | 反我国法律法规的一切平台研发，任何单位和个人使用本软件框架用于产品研发而产生的任何意外
// | 、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、附带
// | 或衍生的损失等)，本团队不承担任何法律责任。本软件框架只能用于公司和个人内部的法律所允
// | 许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
// +----------------------------------------------------------------------

package com.javaweb.admin.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.CommonUtils;
import com.javaweb.common.common.BaseQuery;
import com.javaweb.common.common.BaseServiceImpl;
import com.javaweb.admin.constant.NcServiceLogConstant;
import com.javaweb.admin.entity.NcServiceLog;
import com.javaweb.admin.mapper.NcServiceLogMapper;
import com.javaweb.admin.query.NcServiceLogQuery;
import com.javaweb.admin.service.INcServiceLogService;
import com.javaweb.common.utils.StringUtils;
import com.javaweb.system.utils.ShiroUtils;
import com.javaweb.admin.vo.ncservicelog.NcServiceLogInfoVo;
import com.javaweb.admin.vo.ncservicelog.NcServiceLogListVo;
import com.javaweb.common.utils.DateUtils;
import com.javaweb.common.utils.JsonResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

/**
  * <p>
  *  服务类实现
  * </p>
  *
  * @author 鲲鹏
  * @since 2023-02-13
  */
@Service
public class NcServiceLogServiceImpl extends BaseServiceImpl<NcServiceLogMapper, NcServiceLog> implements INcServiceLogService {

    @Autowired
    private NcServiceLogMapper ncServiceLogMapper;

    /**
     * 获取数据列表
     *
     * @param query 查询条件
     * @return
     */
    @Override
    public JsonResult getList(BaseQuery query) {
        NcServiceLogQuery ncServiceLogQuery = (NcServiceLogQuery) query;
        // 查询条件
        QueryWrapper<NcServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("submit_no","request_body","response_body","response_code","response_result","submit_time","submit_user");
        // queryWrapper.orderByDesc("id");
        if(!StringUtils.isEmpty(ncServiceLogQuery.getDanjNo()))
        {
            queryWrapper.like("submit_no",ncServiceLogQuery.getDanjNo());
        }
        queryWrapper.orderByDesc("submit_time");

        // 获取数据列表
        IPage<NcServiceLog> page = new Page<>(ncServiceLogQuery.getPage(), ncServiceLogQuery.getLimit());
        IPage<NcServiceLog> pageData = ncServiceLogMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            NcServiceLogListVo ncServiceLogListVo = Convert.convert(NcServiceLogListVo.class, x);
            return ncServiceLogListVo;
        });
        return JsonResult.success(pageData);
    }

    @Override
    @SpecifyDataSource(value = DataSourceType.SINESYS)
    public JsonResult getLogList(BaseQuery query) {
        NcServiceLogQuery ncServiceLogQuery = (NcServiceLogQuery) query;
        // 查询条件
        QueryWrapper<NcServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("submit_no","request_body","response_body","response_code","response_result","submit_time","submit_user");
        // queryWrapper.orderByDesc("id");
        if(!StringUtils.isEmpty(ncServiceLogQuery.getDanjNo()))
        {
            queryWrapper.eq("submit_no",ncServiceLogQuery.getDanjNo());
        }
        queryWrapper.orderByDesc("submit_time");

        // 获取数据列表
        IPage<NcServiceLog> page = new Page<>(ncServiceLogQuery.getPage(), ncServiceLogQuery.getLimit());
        IPage<NcServiceLog> pageData = ncServiceLogMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            NcServiceLogListVo ncServiceLogListVo = Convert.convert(NcServiceLogListVo.class, x);
            return ncServiceLogListVo;
        });
        return JsonResult.success(pageData);
    }

    /**
     * 获取详情Vo
     *
     * @param id 记录ID
     * @return
     */
    @Override
    public Object getInfo(Serializable id) {
        NcServiceLog entity = (NcServiceLog) super.getInfo(id);
        // 返回视图Vo
        NcServiceLogInfoVo ncServiceLogInfoVo = new NcServiceLogInfoVo();
        // 拷贝属性
        BeanUtils.copyProperties(entity, ncServiceLogInfoVo);
        return ncServiceLogInfoVo;
    }

    @Override
    public boolean save(NcServiceLog entity) {
        //相同单号的错误日志，一个小时之内只保存3次
        String submitNo = entity.getSubmitNo();
        QueryWrapper<NcServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id","submit_no","request_body","response_body","response_code","response_result","submit_time","submit_user");
        // queryWrapper.orderByDesc("id");
        if(!StringUtils.isEmpty(submitNo))
        {
            queryWrapper.like("submit_no",submitNo);
        }
        //String dateFrom = DateUtil.format(DateUtils.addHours(DateUtils.now(),-1),DateUtils.YYYY_MM_DD_HH_MM_SS);
        //从当前小时开始查询
        String dateFrom = DateUtils.getDate()+" "+DateUtil.hour(DateUtil.date(),true)+":00:00";
        String dateEnd = DateUtil.format(DateUtils.now(),DateUtils.YYYY_MM_DD_HH_MM_SS);
        queryWrapper.between("submit_time",dateFrom,dateEnd);
        queryWrapper.orderByDesc("submit_time");

        // 获取数据列表
        IPage<NcServiceLog> page = new Page<>(1, 20);
        IPage<NcServiceLog> pageData = ncServiceLogMapper.selectPage(page, queryWrapper);
        //如果不是调用康德乐的接口
        if(!entity.getRequestBody().contains("CAH3PL")) {
            if (pageData.getRecords().size() > 12) {
                if (entity.getResponseCode() != null && entity.getResponseCode().equals(pageData.getRecords().get(0).getResponseCode())) {
                    NcServiceLog updateEntity = pageData.getRecords().get(0);
                    //超过3条更新最近的一条
                    updateEntity.setRequestBody(entity.getRequestBody());
                    updateEntity.setResponseBody(entity.getResponseBody());
                    updateEntity.setResponseCode(entity.getResponseCode());
                    updateEntity.setResponseResult(entity.getResponseResult());
                    updateEntity.setSubmitNo(entity.getSubmitNo());
                    updateEntity.setSubmitTime(entity.getSubmitTime());
                    updateEntity.setSubmitUser(entity.getSubmitUser());
                    return super.edit(updateEntity).getCode() == 0 ? true : false;
                }
            }
        }
        return super.save(entity);
    }

    /**
     * 添加、更新记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult edit(NcServiceLog entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
        } else {
        }
        return super.edit(entity);
    }

    /**
     * 删除记录
     *
     * @param entity 实体对象
     * @return
     */
    @Override
    public JsonResult delete(NcServiceLog entity) {
        entity.setMark(0);
        return super.delete(entity);
    }

}